package com.nuanshui.heatedloan.module.builder;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
import com.nuanshui.heatedloan.baseservice.facade.ImageService;
import com.nuanshui.framework.behavior.BehaviorContext;
import com.nuanshui.framework.springContext.SpringContextUtil;
import com.nuanshui.heatedloan.constant.DubboCacheRegion;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.constant.TransactionManagerType;
import com.nuanshui.heatedloan.dubbo.extension.cache.manager.DubboCacheManager;
import com.nuanshui.heatedloan.module.dal.mapper.ModuleMapper;
import com.nuanshui.heatedloan.module.facade.IModuleBuilder;
import com.nuanshui.heatedloan.module.facade.ModuleService;
import com.nuanshui.heatedloan.module.facade.MuseumModuleService;
import com.nuanshui.heatedloan.module.features.IFeatureManager;
import com.nuanshui.heatedloan.module.features.IconFeature;
import com.nuanshui.heatedloan.module.model.*;
import com.nuanshui.heatedloan.userinfo.facade.UserQueryService;
import com.nuanshui.heatedloan.userinfo.facade.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("moduleBuilder")
@Transactional(readOnly = true, value = TransactionManagerType.MODULE_TRANSACTION_MANAGER)
public class ModuleBuilder extends CommonServiceImpl implements IModuleBuilder {

    @Autowired
    private IconFeature iconFeature;

    @Autowired
    private ModuleMapper moduleMapper;

    @Autowired
    private MuseumModuleService museumModuleService;

    @Autowired
    private IFeatureManager featureManager;

    @Autowired
    private ModuleService moduleService;

    private ModuleBuilder moduleBuilder;

    @Autowired
    private DubboCacheManager dubboCacheManager;

    @Reference(url = GlobalParam.BASESERVICE_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.BASESERVICE_DUBBO_SERVER_VERSION)
    private ImageService imageService;


    @Reference(url = GlobalParam.USER_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
    private UserService userService;

    @Reference(url = GlobalParam.USER_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
    private UserQueryService userQueryService;

    private ModuleBuilder getModuleBuilder() {
        if (moduleBuilder == null) {
            moduleBuilder = SpringContextUtil.getBean(ModuleBuilder.class);
        }
        return moduleBuilder;
    }

    @Override
    public Object getResult(ModuleForm form) {
        Object item = null;
        //获取根据模块的名字获取数据

        if (form.getModuleId() != null || (form.getFormType() != null && form.getFormType() == 2)) {
            if (form.getPager().getPageNumber() == 1) {
                item = getData(form);
            } else {
                item = getPageData(form.getModuleId(), form.getId(), form.getPager());
            }
        } else if (StringUtils.isNotEmpty(form.getModuleName()) && (form.getFormType() == null || form.getFormType() == 1)) {
            if (form.getPager().getPageNumber() == 1) {
                item = getMuseumFullModuleByMuseumIdAndModuleName(form);
            } else {
                item = getPageData(form);
            }

        }
        return item;
    }

    public Module getData(ModuleForm moduleForm) {
        Module module = (Module) dubboCacheManager.get(DubboCacheRegion.CHACHE_CONSTANT_MODULE_LIST, moduleForm.getModuleId(),moduleForm.getModuleName());
        if (module==null) {
            module = moduleMapper.getModuleWithFeatureById(moduleForm);
            dubboCacheManager.put(DubboCacheRegion.CHACHE_CONSTANT_MODULE_LIST, module, moduleForm.getModuleId(),moduleForm.getModuleName());
        }
        if (moduleForm.getIsEditRequest() != null && moduleForm.getIsEditRequest() == 1) {
            //log.info(">>>>>>>>>当前执行的是后台编辑的操作<<<<<<<<<<<<<<<<<<<<<<<<<<<");
            return module;
        }
        if (module != null && module.getList() != null) {
            //添加权限
            String userId = (String) BehaviorContext.getContext().get("userId");
            //MuseumOrganizationVO museumOrganizationVO = museumOrganizationService.getMuseumOrganizationByUserId(userId);
            //User user = userQueryService.load(userId);
            //boolean hasAdminAuth = UserAuthUtil.hasAuth(user.getAuth(), UserAuthType.USERAUTHTYPE_MUSEUM_ADMIN);
            //long currentFlag=0;
            if (userId != null && !"".equals(userId)) {
                Map<String, Object> maps = new HashMap<String, Object>();
                module.setExtData(maps);
            }

            for (Feature feature : module.getList()) {
                //log.info("当前builder的模块是>>>>>>>>>>>>>>>>>>>>>>>>" + module.getName()+"下的:"+feature.getName()+ "这个feature<<<<<<<<<<<<<<<<<<<<<<<<<<<");
                List<FeatureItem> items = moduleMapper.getFeatureItems(feature.getFeatureId());
                feature.setInternalData(items);

                FeatureForm form = new FeatureForm();
                form.setModule(module);
                form.setPager(moduleForm.getPager());
                form.setItem(feature);
                form.setFeatureId(moduleForm.getId());
                form.setModuleForm(moduleForm);

                featureManager.handleFeature(form);
            }
        }

        return module;
    }

    public List<Feature> getPageData(Integer moduleId, String featureId, Pageable pager) {
        Feature item = getModuleMoreDataById(moduleId, featureId, pager);
        List<Feature> listModules = new ArrayList<Feature>();
        listModules.add(item);
        return listModules;
    }

    public Feature getModuleMoreDataById(Integer moduleId, String featureId, Pageable pager) {

        Feature item = null;

        ModuleForm moduleForm = new ModuleForm();
        moduleForm.setModuleId(moduleId);


        Module module = moduleMapper.getModuleWithFeatureById(moduleForm);

        if (module.getNoMoreData() == null || module.getNoMoreData() == 0) {
            item = moduleService.getFeatureByFeatureId(featureId);
            FeatureForm form = new FeatureForm();
            form.setItem(item);
            form.setModule(module);
            form.setPager(pager);
            featureManager.handleFeature(form);
        }

        return item;
    }


    // ----------------------------- 上面的都是寻宝考过来的目前没有用到 2016年12月27日20:28:11--------------

    public Module getMuseumFullModuleByMuseumIdAndModuleName(ModuleForm moduleForm) {
        //先获取到模块名字对应的模块数据
        Module module = getModuleBuilder().getMuseumFullModuleByModuleForm(moduleForm);

        if (module != null && !module.getList().isEmpty()) {
            //去除掉不希望回显的feature
            if (StringUtils.isNotEmpty(moduleForm.getEvictModuleIds())) {
                evictFeature(moduleForm.getEvictModuleIds(), module.getList());
            }

            Iterator<Feature> it = module.getList().iterator();
            while (it.hasNext()) {
                Feature feature = it.next();
                //获取每一个feature的feauterItem的数据
                List<FeatureItem> items = getModuleBuilder().getFeatureItems(feature.getFeatureId());
                feature.setInternalData(items);

                FeatureForm form = new FeatureForm();

                module.setMuseumId(moduleForm.getMuseumId());
                form.setIterator(it);
                form.setModule(module);
                form.setModuleForm(moduleForm);
                form.setPager(moduleForm.getPager());
                form.setItem(feature);

                featureManager.handleFeature(form);
            }
        }

        return module;
    }

    /**
     * 编辑的时候，去除掉不惜要的feature回显
     *
     * @param evictModuleId
     * @param list
     * @author Gonzo
     * @date 2016年12月9日下午1:12:41
     * @since 1.0.0
     */
    private void evictFeature(String evictModuleId, List<Feature> list) {
        String ids[] = evictModuleId.split(",");
        List<String> strLis = Arrays.asList(ids);
        Iterator<Feature> iter = list.iterator();
        while (iter.hasNext()) {
            Feature feature = iter.next();

            //由于展厅描述里面有一个type，在描述的时候不需要，这里就将他去掉。。。。
            if (100 == feature.getModuleId()) {
                if (feature.getExtData() != null) {
                    ExtDataModule extData = JSON.parseObject(feature.getExtData(), ExtDataModule.class);
                    if (1 == extData.getTpl()) {
                        feature.setExtData(null);
                    }
                }
            }
            if (strLis.contains(feature.getModuleId() + "")) {
                iter.remove();
            }
        }
    }

    public Module getMuseumFullModuleByModuleForm(ModuleForm moduleForm) {
        String museumId = moduleForm.getMuseumId();
        String moduleName = moduleForm.getModuleName();
        Module module = (Module) dubboCacheManager.get(DubboCacheRegion.CACHE_CONSTANT_MODULE, museumId, moduleName);
        if (module == null) {
            module = museumModuleService.getMuseumFullModuleByMuseumIdAndModuleName(moduleForm);
            dubboCacheManager.put(DubboCacheRegion.CACHE_CONSTANT_MODULE, module, museumId, moduleName);
        }
        setModuleInfo(moduleForm, module);
        return module;
    }

    /**
     * 设置一些module需要的特殊数据
     *
     * @param moduleForm
     * @param module
     * @author Gonzo
     * @date 2017年2月21日下午2:21:01
     * @since 1.3.0
     */
    private void setModuleInfo(ModuleForm moduleForm, Module module) {

    }

    @SuppressWarnings("unchecked")
    public List<FeatureItem> getFeatureItems(int featureId) {
        List<FeatureItem> list = (List<FeatureItem>) dubboCacheManager.get(DubboCacheRegion.CACHE_CONSTANT_FEATURELIST, featureId);
        if (list == null) {
            list = moduleMapper.getFeatureItems(featureId);
            dubboCacheManager.put(DubboCacheRegion.CACHE_CONSTANT_FEATURELIST, list, featureId);
        }
        return list;
    }

    public List<Feature> getPageData(ModuleForm moduleForm) {
        Feature item = getMuseumPageData(moduleForm);
        List<Feature> listModules = new ArrayList<Feature>();
        if (item != null && item.getData() != null) {
            listModules.add(item);
        }
        return listModules;
    }

    //获取下拉刷新的数据
    public Feature getMuseumPageData(ModuleForm moduleForm) {
        //先获取到模块名字对应的模块数据
        Module module = museumModuleService.getMuseumFullModuleByMuseumIdAndModuleName(moduleForm);
        Feature item = null;
        //如果有更多的数据。
        if (module.getNoMoreData() == null || module.getNoMoreData() == 0) {
            //获取到要获取更多数据的那个模块
            item = moduleService.getFeatureByFeatureId(moduleForm.getId());
            if (item == null) return null;
            FeatureForm form = new FeatureForm();
            module.setMuseumId(moduleForm.getMuseumId());

            form.setModuleForm(moduleForm);
            form.setItem(item);
            form.setModule(module);
            form.setPager(moduleForm.getPager());
            featureManager.handleFeature(form);
        }

        return item;
    }
}
